package dmitrygusev.ratings.services;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import dmitrygusev.ratings.model.Movie;

public class RatingQueryService {

	private static final Logger logger = Logger.getLogger(RatingQueryService.class);
	
	public static enum SearchMode {
		BY_TITLE, FULLTEXT
	}

	public List<Movie> execute(SearchMode searchMode, String query, AbstractSource... sources) {
		List<Movie> result = new ArrayList<Movie>();

		if (sources != null) {
			for (AbstractSource source : sources) {
				try {
					List<Movie> movies = new ArrayList<Movie>();
					
					source.fetchRawMovies(query, movies);
					
					for (Movie movie : movies) {
						movie.setSource(source.getName());

						if (searchMode == SearchMode.FULLTEXT
							|| (searchMode == SearchMode.BY_TITLE && Matcher.matchesByTitle(movie, query))) {
							Matcher.normalizeTitles(movie);
							
							source.fetchMovieDetails(movie);
							
							result.add(movie);
						}
					}

				} catch (Exception e) {
					logger.error("Error fetching results from " + source.getName() + ": " + e);
				}
			}
		}
		
		return result;
	}

}
